#!/bin/bash

# 设置安装目录
MYSQL_INSTALL_DIR=/usr/local/mysql

# 下载并解压 MySQL 8.0 安装包
apt install -y unzip libaio1 numactl libtinfo5
cd /tmp
rm mysql*
wget https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.31-linux-glibc2.12-x86_64.tar.xz
tar -xf mysql-8.0.31-linux-glibc2.12-x86_64.tar.xz
sudo mkdir -p ${MYSQL_INSTALL_DIR}
sudo mv mysql-8.0.31-linux-glibc2.12-x86_64/* ${MYSQL_INSTALL_DIR}
sudo rm -rf mysql-8.0.31-linux-glibc2.12-x86_64

# 添加 MySQL 用户和组
sudo groupadd mysql
sudo useradd -r -g mysql mysql

# 配置 MySQL
sudo ${MYSQL_INSTALL_DIR}/bin/mysqld --initialize --user=mysql --basedir=${MYSQL_INSTALL_DIR} --datadir=${MYSQL_INSTALL_DIR}/data
sudo ${MYSQL_INSTALL_DIR}/bin/mysql_ssl_rsa_setup --datadir=${MYSQL_INSTALL_DIR}/data

# 启动 MySQL 服务器
sudo ${MYSQL_INSTALL_DIR}/bin/mysqld_safe --user=mysql &

# 等待 MySQL 启动完成
while ! sudo ${MYSQL_INSTALL_DIR}/bin/mysqladmin ping -u root -p${MYSQL_ROOT_PASSWORD:=wowmanage.cn} --silent; do
  sleep 1
done

# 设置默认密码和其他安全选项
sudo ${MYSQL_INSTALL_DIR}/bin/mysql_secure_installation <<EOF

y
${MYSQL_ROOT_PASSWORD}
${MYSQL_ROOT_PASSWORD}
y
y
y
y
EOF

# 打印 MySQL 版本信息
echo "MySQL version:"
sudo ${MYSQL_INSTALL_DIR}/bin/mysql --version
